package com.rsk.shiro.jwt;


import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Lazy;

import com.rsk.redis.RedisUtils;
import com.rsk.shiro.common.ShiroConst;

@Service
public class JwtRealm extends AuthorizingRealm {
	
    @Autowired
    @Lazy
    private RedisUtils redisUtils;
	
    /**
     * 大坑，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    	String token = (String) principalCollection.getPrimaryPrincipal();
    	System.out.println(token+"111111111");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		Set<String> stringSet = new HashSet<>();
		stringSet.add("users:get");
		simpleAuthorizationInfo.setStringPermissions(stringSet);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        // 解密获得account，用于和数据库进行对比
        String account = JwtUtil.getClaim(token, "account");
    	// 开始认证，要AccessToken认证通过，且Redis中存在RefreshToken，且两个Token时间戳一致
		if (JwtUtil.verify(token) && redisUtils.hasKey(ShiroConst.shiro_refresh + account)) {
			// 获取RefreshToken的时间戳
			String currentTimeMillisRedis = redisUtils.get(ShiroConst.shiro_refresh+ account).toString();
			// 获取AccessToken时间戳，与RefreshToken的时间戳对比
			if (JwtUtil.getClaim(token, ShiroConst.current_time_millis).equals(currentTimeMillisRedis)) {
				return new SimpleAuthenticationInfo(token, token, "jwtRealm");
			}
		}
		throw new AuthenticationException("Token已过期(Token expired or incorrect.)");
    }
}
